/**
 * 
 */
package wong.board.client.widgets;

import java.util.List;
import java.util.Set;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author wong
 * 
 */
public class DataList extends Widget {
	private final String id;
	private Element list;

	public DataList(String id) {
		this.id = id;
		list = DOM.createDiv();
		setElement(list);
		setVisible(false);
	}

	public String getId() {
		return id;
	}

	public void setData(JSONArray data) {
		StringBuffer buffer = createDataList(id);
		int size = data.size();
		for (int i = 0; i < size; i++) {
			appendOption(buffer, null, data.get(i).isString().stringValue());
		}
		finishDataList(buffer);
	}

	public void setData(JSONObject data) {
		StringBuffer buffer = createDataList(id);
		Set<String> keySet = data.keySet();
		for (String key : keySet) {
			appendOption(buffer, key, data.get(key).isString().stringValue());
		}
		finishDataList(buffer);
	}

	public void setData(List<Option> options) {
		StringBuffer buffer = createDataList(id);
		for (Option option : options) {
			appendOption(buffer, option.label, option.value);
		}
		finishDataList(buffer);
	}

	public void clearData() {
		list.setInnerHTML("");
	}

	private StringBuffer createDataList(String id) {
		return new StringBuffer("<datalist id='" + id + "'>");
	}

	private void appendOption(StringBuffer buffer, String label, String value) {
		buffer.append("<option");
		if (label != null) {
			buffer.append(" label='" + label + "'");
		}
		buffer.append(" value='" + value + "'></option>");
	}

	private void finishDataList(StringBuffer buffer) {
		buffer.append("</datalist>");
		list.setInnerHTML(buffer.toString());
	}

	public static class Option {
		public String label;
		public String value;

		public Option(String label, String value) {
			this.label = label;
			this.value = value;
			if (this.value == null)
				throw new NullPointerException("value is null");
		}

		public Option(String value) {
			this(null, value);
		}
	}

}
